<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ishowshao
 * Date: 12-10-22
 * Time: 下午1:25
 * To change this template use File | Settings | File Templates.
 */
$path = 'index.php'; //根目录

function dir_walk_recursive($dir, $callback, $processDir = false) {
    if ($handle = opendir($dir)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path = $dir . '/' . $file;
                if (is_dir($path)) {
                    if ($processDir) {
                        call_user_func($callback, $file, $path);
                    }
                    dir_walk_recursive($path, $callback);
                } else {
                    call_user_func($callback, $file, $path);
                }
            }
        }
        closedir($handle);
    }
}

function countOne($content) {
    $array = explode("\n", $content); //分割成数组
    $count = 0; /* 计数器 */
    $stat = 0; //是否进入多行注释
    $statCount = 0;
    foreach ($array as $line) {
        if (preg_match('/\/\/.+$/', $line)) {
            $count++; //计数器
        } elseif (preg_match('/\/\*.+\*\//', $line)) {
            $count++;
        } elseif (preg_match('/\/\*\*/', $line)) {
            $stat = 1;
        } elseif (preg_match('/\*\//', $line)) {
            if ($stat == 1) {
                $stat = 2;
            }
        }

        if ($stat == 1) {
            $statCount++;
        }
        if ($stat == 2) {
            $statCount++;
            $stat = 0;
            $count += $statCount;
            $statCount = 0;
        }
    }
    return $count; //
}

function callback($file, $path) {
    global $gCount;
    global $gRowCount;
    $info = pathinfo($path);
    if (isset($info['extension'])) {
        $extension = $info['extension'];
        if ($extension == 'js' || $extension == 'html' || $extension == 'css') {
            $content = file_get_contents($path);
            $count = countOne($content);
            $gCount += $count;
            $gRowCount += count(explode("\n", $content));
            echo $path, "\n", $count, "\n";
        }
    }
}

$gCount = 0;
$gRowCount = 0;

dir_walk_recursive('/Users/ishowshao/Documents/boss2.5.6.1/app', 'callback');

echo $gCount, "\n", $gRowCount, "\n", sprintf('%.2f%%', ($gCount / $gRowCount) * 100), "\n";

